package com.ls.lserp.modules.order.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.FileUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.SystemPath;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.order.entity.AuditInfo;
import com.ls.lserp.modules.order.entity.Quotation;
import com.ls.lserp.modules.order.service.QuotationService;
import com.ls.lserp.modules.sys.utils.SystemMessageUtils;

import freemarker.template.Configuration;
import freemarker.template.TemplateException;
import groovy.util.ResourceException;

/**
 * @ClassName: QuotationController
 * @Description:
 * 
 * @author 许天航
 * @date 2017年01月09日
 *
 */

@Controller
@RequestMapping(value = "${adminPath}/quotation/message/")
public class QuotationController extends BaseController {

	@Autowired
	private QuotationService quotationService;
	@Autowired
	Configuration freemarkerConfiguration;

	@ModelAttribute
	public Quotation get(@RequestParam(required = false) String id) {

		// 判断id是否为空
		if (StringUtils.isNotBlank(id)) {

			// 执行查询语句 查询基本信息
			return quotationService.findByID(Long.parseLong(id));
		} else {

			// 若为空，实例化
			return new Quotation();
		}
	}

	/**
	 * 仓库一览画面
	 * 
	 * 
	 * @return
	 */
	@RequestMapping(value = { "" })
	public String quotation() {

		return "modules/order/quotation";

	}

	/**
	 * 拼接一览画面
	 * 
	 * @param values
	 * 
	 * 
	 * @return
	 */
	@RequiresPermissions("quotation:message:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(Quotation quotation, HttpServletRequest request, HttpServletResponse response, Model model,
			String[] values) throws ResourceException {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		FileUtils filUtils = new FileUtils();
		DateFormat dateForamat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		// ajax回调时使用的一览list名
		request.setAttribute("listNames", "quotation");
		// 画面取得的检索项目
		String offerNO = quotation.getOfferNO();
		String styleNO = quotation.getStyleNO();
		String styleNameCN = quotation.getStyleNameCN();
		String styleCustomerName = quotation.getStyleCustomerName();
		String ulSelected = quotation.getUlSelected();
		// 日期
		String dateFrom = quotation.getDateFrom();
		// 日期
		String dateTo = quotation.getDateTo();
		String strUri = request.getContextPath() + Global.getAdminPath();

		// 拼接字符串供分页使用
		String searchParam = "&offerNO=" + offerNO + "&styleNO=" + styleNO + "&styleNameCN=" + styleNameCN
				+ "&styleCustomerName=" + styleCustomerName + "&dateFrom=" + dateFrom + "&dateTo=" + dateTo + "&ulSelected="
				+ ulSelected;
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam);
		// 查询一览页面数据
		Page<Quotation> page = quotationService.findQuotationList(new Page<Quotation>(request, response), quotation);
		// 读取系统路径
		String basePath = SystemPath.getClassPath();
		String tempFilePath = "//" + basePath + "templates//demoHtml//quotationList.txt";
		// 读取文件生成字符串
		String quotationHtml = readTxtFile(tempFilePath);
		String createUser = "";
		String strHtml = "";
		int pageNo = 0;
		if (!"".equals(quotationHtml)) {
			for (int i = 0; i < page.getList().size(); i++) {
				quotationHtml = filUtils.readFileToHtml(tempFilePath);
				// 画面No
				pageNo = (page.getPageNo() - 1) * page.getPageSize() + (i + 1);
				quotationHtml = quotationHtml.replace("pageNo", "" + pageNo);
				// 分类报价单号
				quotationHtml = quotationHtml.replace("offerNO",
						StringUtils.checkStringNull(page.getList().get(i).getOfferNO()));
				String quotationline = "\"popup('1000px','650px','" + strUri + "/quotation/message/viewQuotation?id="
						+ page.getList().get(i).getId() + "&editFlag=0')\"";
				// 分类id
				quotationHtml = quotationHtml.replace("quotationId", quotationline);
				// 分类客户
				quotationHtml = quotationHtml.replace("styleCustomerName",
						StringUtils.checkStringNull(page.getList().get(i).getStyleCustomerName()));
				// 款式图片
				String styleFile = page.getList().get(i).getStyleFile();
				if (styleFile == null || styleFile == "") {
					styleFile = "/fragsmart-erp/static/images/pic-none.jpg";
				}
				quotationHtml = quotationHtml.replace("styleFile", StringUtils.checkStringNull(styleFile));
				// 分类款号
				quotationHtml = quotationHtml.replace("styleNO",
						StringUtils.checkStringNull(page.getList().get(i).getStyleNO()));
				// 分类款式名称
				quotationHtml = quotationHtml.replace("styleNameCN",
						StringUtils.checkStringNull(page.getList().get(i).getStyleNameCN()));
				// 分类款式类型
				quotationHtml = quotationHtml.replace("styleCatgoryCN",
						StringUtils.checkStringNull(page.getList().get(i).getStyleCatgoryCN()));
				// 分类报价类型
				quotationHtml = quotationHtml.replace("offerTypeCN",
						StringUtils.checkStringNull(page.getList().get(i).getOfferTypeCN()));
				// 分类报价数量
				quotationHtml = quotationHtml.replace("offerQuantity",
						StringUtils.checkStringNull(page.getList().get(i).getOfferQuantity() + ""));
				// 分类报价金额
				DecimalFormat decimalFormat = new DecimalFormat("#,##0.00");
				quotationHtml = quotationHtml.replace("offerAmount",
						decimalFormat.format(page.getList().get(i).getOfferAmount()));
				// 创建人
				createUser = StringUtils.checkStringNull(page.getList().get(i).getCreateBy().getFirstName());
				quotationHtml = quotationHtml.replace("createUser", createUser);
				// 创建日期
				dateForamat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				Date createDate = page.getList().get(i).getCreateDate();
				quotationHtml = quotationHtml.replace("createDate", dateForamat.format(createDate));
				strHtml += quotationHtml;
			}
		}
		listMap.put("quotation", strHtml);
		listMap.put("page", page.getHtml());
		// ajax返回结果
		return renderString(response, listMap);
	}

	/**
	 * 拼接款式一览画面
	 * 
	 * @param values
	 * 
	 * 
	 * @return
	 * @throws TemplateException
	 * @throws IOException
	 */
	@RequiresPermissions("quotation:message:view")
	@RequestMapping(value = { "searchStyleList" })
	@ResponseBody
	public String searchStyleList(Quotation quotation, HttpServletRequest request, HttpServletResponse response,
			Model model, String[] values) throws Exception {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute("listNames", "style");
		// 画面取得的检索项目
		String styleNameCN = quotation.getStyleNameCN();
		String styleCatgoryCD = quotation.getStyleCatgoryCD();
		String styleYear = quotation.getStyleYear();
		String styleCustomerName = quotation.getStyleCustomerName();
		// 拼接字符串供分页使用
		String searchParam = "&styleNameCN=" + styleNameCN + "&styleCatgoryCD=" + styleCatgoryCD + "&styleYear=" + styleYear
				+ "&styleCustomerName=" + styleCustomerName;
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam);
		// 查询一览页面数据
		Page<Quotation> page = quotationService.findStyleList(new Page<Quotation>(request, response), quotation);
		String strHtml = "";
		Map<String, Object> map = new HashedMap();
		map.put("styleList", page.getList());
		map.put("pageNo", page.getPageNo());
		map.put("pageSize", page.getPageSize());
		strHtml = FreeMarkerTemplateUtils
				.processTemplateIntoString(freemarkerConfiguration.getTemplate("quotationStyleList.ftl"), map);
		listMap.put("style", strHtml);
		listMap.put("page", page.getHtml());
		listMap.put("quotation", quotation);
		// ajax返回结果
		return renderString(response, listMap);
	}

	/**
	 * 
	 * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
	 * 3：读取到输入流后，需要读取生成字节流
	 * 
	 * @param filePath
	 * @return html
	 */
	public String readTxtFile(String filePath) {
		String strHtml = "";
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			// 判断文件是否存在
			if (file.isFile()) {
				InputStreamReader read = new InputStreamReader(
						// 考虑到编码格式
						new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lingText = null;
				while ((lingText = bufferedReader.readLine()) != null) {
					strHtml += lingText;
				}
				read.close();
			} else {

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strHtml;
	}

	/**
	 * 创建报价单信息窗口
	 * 
	 * @return
	 */

	@RequestMapping(value = "createQuotation")
	public String createQuotation(Quotation quotation, HttpServletRequest request, HttpServletResponse response,
			Model model) {

		model.addAttribute("quotation", quotation);
		return "modules/order/quotationCreate";

	}

	/**
	 * 选择款式信息窗口
	 * 
	 * @return
	 */

	@RequestMapping(value = "createStyle")
	public String createStyle(Quotation quotation, HttpServletRequest request, HttpServletResponse response,
			Model model) {

		model.addAttribute("quotation", quotation);
		return "modules/order/quotationCreate2";

	}

	/**
	 * 编辑报价单信息窗口
	 * 
	 * @return
	 */
	@RequiresPermissions("quotation:message:view")
	@RequestMapping(value = "editQuotation")
	public String editQuotation(Quotation quotation, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		// String flag = quotation.getEditFlag();
		quotation = quotationService.findQuotation(quotation);
		// quotation.setEditFlag(flag);
		model.addAttribute("quotation", quotation);
		return "modules/order/quotationCreate";

	}

	/**
	 * 创建编辑保存仓库信息
	 * 
	 * @return
	 * @throws ParseException
	 * @throws ResourceException
	 */
	@RequiresPermissions("quotation:message:edit")
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(Quotation quotation, HttpServletRequest request, HttpServletResponse response, Model model) {

		// 判断id是否为null （判断新建或修改）
		if (quotation.getId() != null) {
			// 编辑数据
			// 判断数据是否删除
			Quotation quotationNew = get(quotation.getId().toString());
			// 判断数据是否删除
			if (quotationNew == null || BaseEntity.DEL_FLAG_DELETE.equals(quotationNew.getDeleteFlag())) {
				// 返回提示信息
				return renderString(response, AjaxDone.error(getText("warehouse_edit_save_msg_fail")));
			}

			// 排他处理
			if (quotation.getVersion() == get(quotation.getId().toString()).getVersion()) {

				// 版本号加1
				quotation.setVersion(quotation.getVersion() + 1);
			} else {

				// 返回提示信息
				return renderString(response, AjaxDone.error(getText("warehouse_edit_save_msg_fail")));
			}
		}

		try {
			// 保存数据
			quotationService.saveQuotation(quotation);
			// 保存成功返回提示信息
			return renderString(response, AjaxDone.ok(SystemMessageUtils.getMessageName("warehouse_edit_save_msg_success")));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			// 保存失败返回提示信息
			return renderString(response, AjaxDone.ok(SystemMessageUtils.getMessageName("settlement_save_fail")));
		}

	}

	/**
	 * 查看一条报价单信息
	 * 
	 * @return
	 */
	@RequiresPermissions("quotation:message:view")
	@RequestMapping(value = "viewQuotation")
	public String viewQuotation(Quotation quotation, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		String flag = quotation.getEditFlag();
		quotation = quotationService.findQuotation(quotation);
		quotation.setEditFlag(flag);
		model.addAttribute("quotation", quotation);
		return "modules/order/quotationShow";

	}

	/**
	 * 审核页面
	 * 
	 * @param quotation
	 * @param model
	 * @return
	 */
	@RequiresPermissions("quotation:message:audit")
	@RequestMapping(value = "audit")
	public String audit(Quotation quotation, Model model) {

		// 履历一览取得
		AuditInfo auditInfo = new AuditInfo();
		// id
		auditInfo.setAuditRelateId(quotation.getId());
		// 阶段
		auditInfo.setAuditPhaseCd(ResourcesUtil.getConfig("audit_phase_quotation"));
		AuditInfo resultInfo = quotationService.findAuditInfo(auditInfo);

		resultInfo.setAuditRelateId(quotation.getId());

		resultInfo.setAuditRelateNo(quotation.getOfferNO());

		resultInfo.setAuditPhaseCd(ResourcesUtil.getConfig("audit_phase_quotation"));

		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("auditInfo", resultInfo);

		// 返回页面地址
		return "modules/order/auditInfo";
	}

	/**
	 * 保存履历信息
	 * 
	 * @param auditInfo
	 * @param request
	 * @param model
	 * @param response
	 * @return
	 * @throws ResourceException
	 */
	@RequiresPermissions("quotation:message:edit")
	@RequestMapping(value = "saveAudit")
	@ResponseBody
	public String saveAudit(AuditInfo auditInfo, HttpServletRequest request, Model model, HttpServletResponse response,
			HttpSession session) throws ResourceException {

		// 是否需要更新样品需求状态
		boolean isUpdateStatus = false;

		// 判断数据是否删除
		Quotation quotation = get(Long.toString(auditInfo.getAuditRelateId()));
		// 判断数据是否删除
		if (quotation.getOfferNO() == null || BaseEntity.DEL_FLAG_DELETE.equals(quotation.getDeleteFlag())) {
			// 返回提示信息
			return renderString(response,
					AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
		}

		// 审核结果已经通过,返回错误提示信息
		AuditInfo pAuditResult = new AuditInfo();
		pAuditResult.setAuditPhaseCd(auditInfo.getAuditPhaseCd());
		pAuditResult.setAuditRelateId(auditInfo.getAuditRelateId());
		if (quotationService.getAuditResult(pAuditResult) > 0) {
			// 返回提示信息
			return renderString(response,
					AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
		}

		// 保存样品数据
		quotationService.saveAuditInfo(auditInfo, isUpdateStatus);

		// 保存成功返回提示信息
		return renderString(response, AjaxDone.ok(SystemMessageUtils.getMessageName("audit_ok_msg")));

	}

	/**
	 * 查看一条款式信息
	 * 
	 * @return
	 */
	@RequiresPermissions("quotation:message:view")
	@RequestMapping(value = "getStyle")
	@ResponseBody
	public String getStyle(Quotation quotation, HttpServletRequest request, HttpServletResponse response, Model model) {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		quotation = quotationService.getStyle(quotation);
		listMap.put("styleFileList", quotation.getStyleFileList());
		listMap.put("styleNO", quotation.getStyleNO());
		listMap.put("styleCustomerName", quotation.getStyleCustomerName());
		listMap.put("styleNameCN", quotation.getStyleNameCN());
		listMap.put("styleFile", quotation.getStyleFile());
		return renderString(response, listMap);

	}

	/**
	 * 联动返回单耗
	 * 
	 * @param code
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "unitCost")
	@ResponseBody
	public String unitCost(String code, Model model, HttpServletResponse response) {

		List<Quotation> unitCostList = quotationService.findUnitCostList(Long.parseLong(code));

		return renderString(response, unitCostList);

	}

	/**
	 * 联动返回面料
	 * 
	 * @param code
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "material")
	@ResponseBody
	public String material(Long id, Model model, HttpServletResponse response) {
		// Map<Object, Object> listMap = new HashMap<Object, Object>();
		Quotation quotation = quotationService.getUnitCost(id);
		List<Quotation> materialList = quotation.getQuotationMaterialList();
		// listMap.put("quotation", quotation);
		return renderString(response, materialList);

	}

	/**
	 * 获取图片集
	 * 
	 * @return
	 */
	@RequiresPermissions("quotation:message:view")
	@RequestMapping(value = "findImageList")
	@ResponseBody
	public String findImageList(Quotation quotation, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		String allFlie = quotation.getStyleFile();
		String imageHtml = "";
		Quotation quotationObj = quotationService.getStyle(quotation);
		// 款式图片list生成
		List<Quotation> imageListTemp = quotationObj.getStyleFileList();
		map.put("imageList", imageListTemp);
		map.put("allFlie", allFlie);
		// 生成款式图片的HTML
		imageHtml = createHtml(map, "imageUrlList.ftl");
		listMap.put("imageListHtml", imageHtml);
		return renderString(response, listMap);

	}

	/**
	 * @Title: 生成HTML
	 * @return HTML
	 */
	public String createHtml(Map<String, Object> map, String fileName) {
		String tempHtml = "";
		try {
			tempHtml = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate(fileName), map);
		} catch (Exception e) {
			return tempHtml;
		}
		return tempHtml;
	}

}